package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.CreateOrderRequest;
import com.luo.backend.dto.OrderResponse;
import com.luo.backend.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * 订单管理控制器
 */
@RestController
@RequestMapping("/api/v1/orders")
public class OrderController {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 创建订单
     */
    @PostMapping
    public ApiResponse<OrderResponse> createOrder(@Valid @RequestBody CreateOrderRequest request) {
        try {
            Long userId = getCurrentUserId();
            OrderResponse order = orderService.createOrder(userId, request);
            return ApiResponse.created("订单创建成功", order);
        } catch (Exception e) {
            logger.error("创建订单失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户订单列表
     */
    @GetMapping
    public ApiResponse<Map<String, Object>> getOrders(
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int limit) {
        try {
            Long userId = getCurrentUserId();
            Map<String, Object> result = orderService.getUserOrders(userId, status, page, limit);
            return ApiResponse.success(result);
        } catch (Exception e) {
            logger.error("获取订单列表失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public ApiResponse<OrderResponse> getOrderById(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            OrderResponse order = orderService.getOrderById(userId, id);
            return ApiResponse.success(order);
        } catch (Exception e) {
            logger.error("获取订单详情失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 支付订单
     */
    @PutMapping("/{id}/pay")
    public ApiResponse<OrderResponse> payOrder(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            OrderResponse order = orderService.payOrder(userId, id);
            return ApiResponse.success("支付成功", order);
        } catch (Exception e) {
            logger.error("支付订单失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public ApiResponse<OrderResponse> cancelOrder(
            @PathVariable Long id,
            @RequestBody Map<String, String> request) {
        try {
            Long userId = getCurrentUserId();
            String reason = request.get("reason");
            if (reason == null || reason.trim().isEmpty()) {
                return ApiResponse.error("取消原因不能为空");
            }
            OrderResponse order = orderService.cancelOrder(userId, id, reason);
            return ApiResponse.success("订单取消成功", order);
        } catch (Exception e) {
            logger.error("取消订单失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 申请退款
     */
    @PutMapping("/{id}/refund")
    public ApiResponse<OrderResponse> refundOrder(
            @PathVariable Long id,
            @RequestBody Map<String, String> request) {
        try {
            Long userId = getCurrentUserId();
            String reason = request.get("reason");
            if (reason == null || reason.trim().isEmpty()) {
                return ApiResponse.error("退款原因不能为空");
            }
            OrderResponse order = orderService.refundOrder(userId, id, reason);
            return ApiResponse.success("退款申请成功", order);
        } catch (Exception e) {
            logger.error("申请退款失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 确认收货
     */
    @PostMapping("/{id}/confirm")
    public ApiResponse<OrderResponse> confirmReceipt(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            logger.info("用户确认收货 - 订单ID: {}, 用户ID: {}", id, userId);
            
            OrderResponse order = orderService.confirmReceipt(userId, id);
            return ApiResponse.success("确认收货成功", order);
        } catch (IllegalArgumentException e) {
            // 业务异常（如状态不对、权限不足等）
            logger.warn("确认收货失败 - 订单ID: {}, 原因: {}", id, e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            // 系统异常
            logger.error("确认收货系统异常 - 订单ID: {}", id, e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof Long) {
            return (Long) principal;
        }
        throw new RuntimeException("未能获取当前用户信息");
    }
}

